//
//  VoiceReadDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2021/4/20.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "VoiceReadDetailViewController.h"
#import "VoiceItemContentViewController.h"
#import "VoiceReadDetailCoverView.h"
#import "VoiceReadDetailReplyHeaderView.h"
#import "VoiceItemContentToolView.h"

#import "VoiceReadDetailItemModel.h"
#import "VoiceReadCommentListModel.h"
@interface VoiceReadDetailViewController ()<VoiceItemContentToolViewDelegate>
@property (nonatomic,strong)VoiceReadDetailCoverView *coverView;
@property (nonatomic,strong)VoiceReadDetailReplyHeaderView *replyHeaderView;
@property (nonatomic,strong)VoiceItemContentToolView *toolView;
@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)UIImageView *backImgView;
@property (nonatomic,strong)UIImageView *shareImgView;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIButton *shareBtn;

@property (nonatomic,strong)VoiceReadDetailItemModel *dtlModel;

@end

@implementation VoiceReadDetailViewController

- (VoiceItemContentToolView *)toolView{
    if (!_toolView) {
        _toolView = [[VoiceItemContentToolView alloc]init];
        _toolView.delegate = self;
    }
    return _toolView;
}

- (VoiceReadDetailCoverView *)coverView{
    if (!_coverView) {
        _coverView = [[VoiceReadDetailCoverView alloc]init];
    }
    return _coverView;
}
- (VoiceReadDetailReplyHeaderView *)replyHeaderView{
    if (!_replyHeaderView) {
        _replyHeaderView = [[VoiceReadDetailReplyHeaderView alloc]init];
//        _replyHeaderView.delegate = self;
    }
    return _replyHeaderView;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
 
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    
    [self loadDataSource];
//    [self setOtherPlayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateToolBarAtFirst) name:@"updateToolBarAtFirst" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateToolBarAtSecond) name:@"updateToolBarAtSecond" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateToolBarAtLast) name:@"updateToolBarAtLast" object:nil];
}
- (void)updateToolBarAtFirst{
    [self.toolView setCurrentIndex:0];
}
- (void)updateToolBarAtSecond{
    [self.toolView setCurrentIndex:1];
}
- (void)updateToolBarAtLast{
    [self.toolView setCurrentIndex:2];
}


- (JXPagerView *)preferredPagingView{
    return [[JXPagerView alloc] initWithDelegate:self];
}

- (void)setUI{
  
    self.pagerView = [self preferredPagingView];
    self.pagerView.mainTableView.gestureDelegate = self;
    self.pagerView.isListHorizontalScrollEnabled = NO;
    self.pagerView.automaticallyDisplayListVerticalScrollIndicator = NO;
    self.pagerView.pinSectionHeaderVerticalOffset = kNavBarHeight;
    self.pagerView.frame = CGRectMake(0, 0,kScreenW, kScreenH);
    [self.view addSubview:self.pagerView];
    
    self.isHideNavBar = YES;

    self.navView = [[UIView alloc]init];
    self.navView.backgroundColor = [UIColor whiteColor];
    self.navView.alpha = 0;
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(kNavBarHeight);
    }];
//
    self.backImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voice_back_tag"]];
    [self.view addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.top.equalTo(self.view).offset(12 + GK_STATUSBAR_HEIGHT);
    }];

    self.shareImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voice_share_tag"]];
    [self.view addSubview:self.shareImgView];
    [self.shareImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.centerY.equalTo(self.backImgView);
    }];
    
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(100, 60));
    }];

    self.shareBtn = [[UIButton alloc]init];
    [self.shareBtn addTarget:self action:@selector(shareMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shareBtn];
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(100, 60));
    }];
}

- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.voiceId;
    param[@"md5"] = [RPAppManager md5StrWithApi:VoiceDetails];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(VoiceDetails) parames:param success:^(id responseObj) {
        
//        self.footerView.hidden = NO;
//        
        self.dtlModel = [VoiceReadDetailItemModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        
        [self.coverView setDtlModel:self.dtlModel];
        
        [self loadCommentList];
//       
//        NSArray *sourceArray = self.dtlModel.tvoiceResources;
//        
//        if (sourceArray.count > 1) {
//            NSArray *result = [sourceArray sortedArrayUsingComparator:^NSComparisonResult(VoiceReadDetailPlayerModel *_Nonnull obj1, VoiceReadDetailPlayerModel * _Nonnull obj2) {
//                NSInteger seq1 = obj1.seq.intValue;
//                NSInteger seq2 = obj2.seq.intValue;
//                if (seq1 > seq2) {
//                    return NSOrderedDescending;
//                }else if(seq1 < seq2){
//                    return NSOrderedAscending;
//                }
//                return NSOrderedSame;
//            }];
//           self.dtlModel.tvoiceResources = result;
//        }
//                
//        // 判断上层页面再播放
//        if (self.currentModel != nil) {
//            __block NSInteger index = -1;
//            [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                if ([self.currentModel.resourceId isEqualToNumber:obj.resourceId]) {
//                    index = idx;
//                }
//            }];
//            // 判断详情音源文件
//            if (index == -1 && self.currentModel.status != XHPlayerListItemFailed) {
//                self.currentModel.status = XHPlayerListItemFailed;
//            }
//        }else{
//            VoiceReadDetailPlayerModel *videoModel = nil;
//            if (sourceArray.count > 0) {
//                videoModel = self.dtlModel.tvoiceResources.firstObject;
//            }
//            __block NSInteger index = -1;
//            [self.sourceArray enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                // 判断currentModel 到时哪一个
//                if (videoModel != nil && [videoModel.id isEqualToNumber:obj.resourceId]) {
//                    index = idx;
//                }
//            }];
//            if (index != -1) {
//                self.currentModel = self.sourceArray[index];
//            }else{
//                self.currentModel = [self.sourceArray firstObject];
//            }
//            self.currentModel.currentTime = 0;
//            self.currentModel.status = XHPlayerListItemReady;
//          
//            if (index == -1) {
//                [self.player df_playWithAudioId:0];
//            }else{
//                [self.player df_playWithAudioId:index];
//            }
//        }
//        
//        [self.footerView setItemModel:self.currentModel];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)loadCommentList{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:PostNewCommentList];
    param[@"projectId"] = self.voiceId;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = @(1);
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @10;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(PostNewCommentList) parames:param success:^(id responseObj) {
        NSArray *commentList = [VoiceReadCommentListModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateVoiceCommentList" object:nil userInfo:@{@"list":commentList,@"voiceId":self.voiceId}];
    } failure:^(id error) {
         
    }];
}


- (void)shareMethod{
    
}
- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y <= 0) {
          [scrollView setContentOffset:CGPointMake(0, 0)];
      }
      self.navView.alpha = scrollView.contentOffset.y/((kScreenW/4*3) - kNavBarHeight - 20 - 24 - 1);
    
}

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.coverView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return kScreenW/4*3 + 32;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return 44;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.toolView;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    //和categoryView的item数量一致
    return 1;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    VoiceItemContentViewController *vc = [[VoiceItemContentViewController alloc] init];
    return vc;
}

- (void)dealloc{
    
}

#pragma mark - VoiceItemContentToolViewDelegate
- (void)changeToolViewAtIndex:(NSInteger)index{
    [self.pagerView.mainTableView setContentOffset:CGPointMake(0, kScreenW/4*3 + 32) animated:NO];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateContentOffset" object:nil userInfo:@{@"index":@(index)}];
    

}


@end
